<?php

/**
 * 特批发票服务
 * @author yuzy 2015-5-7
 */

namespace common\services\myhtsq;

use common\services\BaseService;
use common\error\ErrorCode;
use common\repositories\myhtsq\SpecialApprovalInvoiceRepository;
use common\models\myhtsq\SpecialApprovalInvoiceModel;
use common\services\common\MyscrmContractSyncDeleteDataService;
use common\services\myhtsq\DocumentService;
use common\support\PageParam;
use common\models\myhtsq\DocumentModel;
use common\support\StringHelper;
use common\services\myhtsq\ContractService;

class SpecialApprovalInvoiceService extends BaseService {

    protected $_invoiceRepository;
    
    /**
     * 构造函数
     */
    public function __construct(SpecialApprovalInvoiceRepository $invoiceRepository) {
        $this->_invoiceRepository = $invoiceRepository;
    }

    /**
     * 特批发票列表
     * @param integer $page 页码
     * @param integer $pageSize 页条数
     * @param string $sortBy 排序字段
     * @param boolean $sortAsc 是否升序
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     * @return array
     */
    public function getSpecialApprovalInvoiceList($pageIndex, $pageSize, $sortBy, $sortAsc, $keyword, $areaId,$fulfil) {
        $pageParam = new PageParam($pageIndex, $pageSize, $sortBy, $sortAsc);

        #区域过滤
        if(empty($areaId)) {
           $areaId = ContractService::filterBusinessUnit(\Yii::$app->user->identity);
        }

        return SpecialApprovalInvoiceRepository::getSpecialApprovalInvoiceList($pageParam, $areaId, $fulfil, $keyword);
    }

    /**
     * 获取特批发票信息
     * @param string $invoiceId
     * @return \common\models\myhtsq\SpecialApprovalInvoiceModel
     */
    public function getSpecialApprovalInvoiceInfo($invoiceId) {
        $entity = SpecialApprovalInvoiceRepository::getSpecialApprovalInvoiceInfo($invoiceId);
        $list = DocumentService::getDocumentListByBusinessId($invoiceId);
        $result['item'] = $entity;
        $result['attachmentList'] = $list;
        return $result;
    }

    /**
     * 新增特批发票
     * @param \common\models\myhtsq\SpecialApprovalInvoiceModel $invoiceModel
     * @return boolean|string   失败|合同Guid
     */
    public function addSpecialApprovalInvoice($invoiceModel, $attachmentList) {
        if ($invoiceModel->validate()) {
            $result = $this->_invoiceRepository->addSpecialApprovalInvoice($invoiceModel);
            if ($result === FALSE) {
                return $this->setAndReturn($this->_invoiceRepository->getErrCode());
            } else {
                // 附件
                $documentService = new DocumentService();
                foreach ($attachmentList as $idx => $value) {
                    $documentModel = new DocumentModel();
                    $documentModel->load($value,'');
                    $documentModel->document_id = StringHelper::uuid();
                    $documentModel->document_ext_name = StringHelper::getFileExtName($documentModel->document_path);
                    $documentModel->business_id = $result;
                    $documentService->addDocument($documentModel);
                }
                return $result;
            }
        } else {
            return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_INVOICE_FORM_VERIFY_FAIL);
        }
    }

    /**
     * 更新特批发票
     * @param \common\models\myhtsq\SpecialApprovalInvoiceModel $invoiceModel
     * @return boolean|string   失败|合同Guid
     */
    public function updateSpecialApprovalInvoice($invoiceModel, $attachmentList) {
        if ($invoiceModel->validate()) {  
            $result = $this->_invoiceRepository->updateSpecialApprovalInvoice($invoiceModel);
            if ($result === FALSE) {
                return $this->setAndReturn($this->_invoiceRepository->getErrCode());
            } else {
                // 原附件列表
                $originalDocumentList = DocumentService::getDocumentListByBusinessId($invoiceModel->special_approval_invoice_id);
                $documentService = new DocumentService();

                foreach ($originalDocumentList as $idx => $value) {
                    $hit = false;
                    foreach ($attachmentList as $idx2 => $value2) {
                        if ($value['document_id'] == $value2['document_id']) {
                            $hit = true;
                            break;
                        }
                    }
                    if ($hit === false) {
                        $documentService->delDocumentById($value['document_id']);
                    }
                }

                foreach ($attachmentList as $idx => $value) {
                    $hit = false;
                    foreach ($originalDocumentList as $idx2 => $value2) {
                        if ($value['document_id'] == $value2['document_id']) {
                            $hit = true;
                            break;
                        }
                    }                    
                    if ($hit === false) {
                        $documentModel = new DocumentModel();
                        $documentModel->load($value,'');
                        $documentModel->document_id = StringHelper::uuid();
                        $documentModel->document_ext_name = StringHelper::getFileExtName($documentModel->document_path);
                        $documentModel->business_id = $invoiceModel->special_approval_invoice_id;
                        $documentService->addDocument($documentModel);
                    }                    

                }
                return $result;
            }
        } else {
            return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_INVOICE_FORM_VERIFY_FAIL);
        }
    }

    /**
     * 根据发票编号删除特批发票
     * @param string $invoiceNumber
     * @return 失败的返回false，成功则返回删除的记录条数
     */    
    public function delSpecialApprovalInvoiceByInvoiceNumber($invoiceNumber)
    {
        /** @var MyscrmContractSyncDeleteDataService $contractSyncDeleteDataService */
        $contractSyncDeleteDataService = \Yii::createObject(MyscrmContractSyncDeleteDataService::className());

        $entity = SpecialApprovalInvoiceRepository::getSpecialApprovalInvoiceByInvoiceNumber($invoiceNumber);
        if (is_null($entity)) {
            return 0;
        }
        $result = $this->_invoiceRepository->delSpecialApprovalInvoiceByInvoiceNumber($invoiceNumber);
        if ($result === FALSE) {
            return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_INVOICE_DELETE_FAIL);
        } else {

            if($result > 0){
                $contractSyncDeleteDataService->addData('myscrm_special_approval_invoice', 'special_approval_invoice_id', $entity->special_approval_invoice_id);
            }

            $needDeleteDocumentData = DocumentService::getDocumentListByBusinessId($entity->special_approval_invoice_id);

            $documentDeleteResult = DocumentService::delDocumentByBusinessId($entity->special_approval_invoice_id);

            if($documentDeleteResult > 0) {
                foreach ($needDeleteDocumentData as $data) {
                    $contractSyncDeleteDataService->addData('myscrm_document', 'document_id', $data['document_id']);
                }
            }

            return $result;
        }
    }
    
    
    /**
     * 导出特批发票
     * @param type $data
     */
    public function exportSpecialApprovalInvoiceList ($data) {
        if (isset($data) && count($data) > 0) {
            $CategoryList = [
                1 => '合同未归档',
                2 => '开票金额与合同应收金额不相等',
                3 => '开票名称与签约客户名称不一致',
                4 => '结算款未支付',
                5 => '合同未归档',
                6 => '开票名称与付款名称不一致'
            ];
            foreach ($data as $k => $v) {
                $category = $v['category'];
                $data[$k]['category_name'] = '';
                if (!is_null($category) && isset($CategoryList[$category])) {
                    $data[$k]['category_name'] = $CategoryList[$category];
                    continue;
                }
            }
        }
        $objPHPExcel = new \PHPExcel();
        //设置当前的sheet
        $objPHPExcel->setActiveSheetIndex(0);
        //设置sheet的name
        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        //设置单元格的值
        $objPHPExcel->getActiveSheet()->setCellValue('A1', '发票id');
        $objPHPExcel->getActiveSheet()->setCellValue('B1', '发票号码');
        $objPHPExcel->getActiveSheet()->setCellValue('C1', '特批类型');
        $objPHPExcel->getActiveSheet()->setCellValue('D1', '兑现责任人');
        $objPHPExcel->getActiveSheet()->setCellValue('E1', '承诺日期');
        $objPHPExcel->getActiveSheet()->setCellValue('F1', '兑现日期');
        $objPHPExcel->getActiveSheet()->setCellValue('G1', '发票抬头');
        $objPHPExcel->getActiveSheet()->setCellValue('H1', '备注');
        $objPHPExcel->getActiveSheet()->setCellValue('I1', '合同签署公司');
        $objPHPExcel->getActiveSheet()->setCellValue('J1', '合同所属区域');

        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['special_approval_invoice_id']); // 发票id
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['invoice_no']); // 发票号码
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['category_name']); //特批类型
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['principal_name']); //兑现责任人
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, empty($val['promise_fulfil_time']) ? "" : date('Y-m-d', strtotime($val['promise_fulfil_time']))); //承诺日期
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, empty($val['actual_fulfil_time']) ? "" : date('Y-m-d', strtotime($val['actual_fulfil_time']))); //兑现日期
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['customer_name']); //发票抬头
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['comment']); //摘要
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['contract_company_name']); //合同签署公司
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['area_name']); //合同签署公司
                $j++;
            }
        }
        
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setVisible(false); //把合同guid 设置为隐藏列
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="特批发票' . date("YmdHis") . '.xls"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
        exit;
    }
    
    
    public function delSpecialApprovalInvoice ($invoiceId) {
        if (empty($invoiceId)) {
            return false;
        }
        return $this->_invoiceRepository->delSpecialApprovalInvoice($invoiceId);
    }
}
